package com.medium.house.controller;

import com.medium.house.biz.HouseInfoBiz;
import com.medium.house.biz.HouseQueryConditionBiz;
import com.medium.house.constant.Constant;
import com.medium.house.entity.HouseInfo;
import com.medium.house.enums.HouseTypeEnum;
import com.medium.house.enums.LeaseTypeEnum;
import com.medium.house.request.HouseInfoRequestDto;
import com.medium.house.request.HouseSellPointRequestDto;
import com.medium.house.response.HouseInfoDto;
import com.medium.house.response.HouseOverView;
import com.medium.house.service.HouseInfoService;
import com.medium.house.utils.Arith;
import com.medium.house.utils.JacksonUtils;
import com.medium.house.utils.ValidatorUtil;
import com.medium.house.vo.ResultVO;
import com.medium.house.vo.ResultVOUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author : wang.yu
 * @Description :
 * @Date: Created in 2018/2/7 0007  20:41
 * @Modified By
 */
@Api(value = "/house/Release",description="房源信息",tags={"房源信息"})
@RestController
@RequestMapping("/api/house/")
@Slf4j
@SuppressWarnings("all")
public class HouseReleaseController {
    @Autowired
    private HouseQueryConditionBiz houseQueryConditionBiz;
    @Autowired
    private HouseInfoBiz houseInfoBiz;
    @Autowired
    private HouseInfoService houseInfoService;

    /**
     * 暂时先这样放着，等全部可配置后，此路径配置到文件中
     */
    @Value("${image.qiniu.default.img}")
    private String default_img;

    @ApiOperation("发布房源")
    @PostMapping(value = "release")
    public ResultVO releaseHouseInfo(@Valid HouseInfoRequestDto houseInfoRequestDto, BindingResult bindingResult){
        log.info("HouseReleaseController releaseHouseInfo houseInfoRequestDto：{}", houseInfoRequestDto);
        HouseInfo houseInfo = new HouseInfo().initialize();
        BeanUtils.copyProperties(houseInfoRequestDto,houseInfo);
        houseInfo.setType(HouseTypeEnum.toEnum(houseInfoRequestDto.getType()));
        if (!ValidatorUtil.isMobile(houseInfoRequestDto.getMobile())){
            return ResultVOUtil.error("手机格式错误");
        }else if (null == houseInfoRequestDto.getSellPrice()){
            if (HouseTypeEnum.toEnum(houseInfoRequestDto.getType()) == HouseTypeEnum.SECONDHAND) {
                return ResultVOUtil.error("请录入期望售价");
            }else if (HouseTypeEnum.toEnum(houseInfoRequestDto.getType()) == HouseTypeEnum.RANTAL) {
                return ResultVOUtil.error("请录入出租价格");
            }
        }else if (!ValidatorUtil.isNumber(houseInfoRequestDto.getSellPrice())){
            if (HouseTypeEnum.toEnum(houseInfoRequestDto.getType()) == HouseTypeEnum.SECONDHAND) {
                return ResultVOUtil.error("期望售价必须是数字");
            }else if (HouseTypeEnum.toEnum(houseInfoRequestDto.getType()) == HouseTypeEnum.RANTAL) {
                return ResultVOUtil.error("出租价格必须是数字");
            }
            return ResultVOUtil.error("价格必须是数字");
        }else if (null == houseInfoRequestDto.getArea()){
            return ResultVOUtil.error("房屋面积录入非法");
        }else if (!ValidatorUtil.isNumber(houseInfoRequestDto.getArea().toString())){
            return ResultVOUtil.error("面积必须是数字");
        }
        if (HouseTypeEnum.toEnum(houseInfoRequestDto.getType()) == HouseTypeEnum.SECONDHAND){
            houseInfo.setAveragePrice(String.valueOf(Arith.div(new BigDecimal(houseInfoRequestDto.getSellPrice()).doubleValue(),houseInfoRequestDto.getArea().doubleValue(),2)));
            houseInfo.setLease(LeaseTypeEnum.OTHER);
        }else {
            houseInfo.setLease(LeaseTypeEnum.toEnum(Integer.parseInt(houseInfoRequestDto.getLease())));
        }
        //参数校验
        if(bindingResult.hasErrors()){
            log.info("HouseReleaseController releaseHouseInfo houseInfoRequestDto hasErrors：{}", bindingResult.getFieldError().getDefaultMessage());
            return ResultVOUtil.error(bindingResult.getFieldError().getDefaultMessage());
        }
        houseInfo.setSearchCondition(houseInfo.getTitle()+""+houseInfo.getCommunityName());
        houseInfo.setHousePicture(default_img);
        if (houseInfoBiz.release(houseInfo) == 0){
            return ResultVOUtil.error("发布房源失败");
        }
        //查询条件
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",houseInfo.getId());
        map.put("openid",houseInfo.getOpenid());
        final ResultVO success = ResultVOUtil.success(map);
        return success;
    }

    @ApiOperation("查询列表")
    @PostMapping(value = "releaseList")
    public ResultVO getRelease(@RequestParam(required=false,defaultValue = "1") int page,
                               @RequestParam(required=false) String openid,
                               @RequestParam Integer type,
                               @RequestParam(required=false,defaultValue = "0") Integer status,
                               @RequestParam(required=false)  String title,
                               @RequestParam(required=false)  String layout,
                               @RequestParam(required=false)  String region,
                               @RequestParam(required=false)  String price,
                               @RequestParam(required=false)  String lease){
        log.info("HouseRoomController getRelease page：{},openid：{},type:{},status:{},title:{},layout:{},region:{},price:{},lease:{}", page,openid,type,status,title,layout,region,price,lease);

        // 后台计算出页码、页数(页大小)
        int offset =(page - 1) * Constant.LIMIT;
        int limit = /*page * */Constant.LIMIT;
        int sort = 2;
        int order = 0;
        List<Map<String,Object>> houseInfoList = houseInfoService.getByPageToOverViewForJoin(offset,limit,sort,order,
                type,1,openid,title,layout,region,price,lease);
        for (Map<String,Object> map: houseInfoList) {
            if (map.get("sellPoint") instanceof String){
                map.put("sellPoint",JacksonUtils.extractList(map.get("sellPoint").toString(),new ArrayList<HouseSellPointRequestDto>()));
            }
        }
        return ResultVOUtil.success(houseInfoList);
    }

    @ApiOperation("上传房源图片")
    @PostMapping(value = "upLoadHousePicture")
    public ResultVO upLoadHousePicture(
            @RequestParam(value = "id",required=false) Long id,
            @RequestParam(value = "openid",required=false) String openid,
            @RequestParam(value = "picture",required=false) MultipartFile picture){
        log.info("HouseReleaseController upLoadHousePicture ==> id:{},openid:{}", id,openid);
        if (StringUtils.isEmpty(id)){
            return ResultVOUtil.error("房屋信息错误");
        }else if (StringUtils.isEmpty(openid)){
            return ResultVOUtil.error("用户信息错误");
        }else if (null == picture){
            return ResultVOUtil.error("请选择照片");
        }
        HouseInfo houseInfo =  houseInfoService.get(id);
        if (null == houseInfo){
            return ResultVOUtil.error("房屋信息不存在");
        }
        try {
            if (houseInfoBiz.upLoadHousePicture(houseInfo,picture) == 0){
                return ResultVOUtil.error("发布房源失败");
            }
        }catch (Exception e) {
            log.error("releaseHouseInfo Exception",e.getMessage());
            return ResultVOUtil.error("连接超时，请稍后再试...");
        }
        return ResultVOUtil.success();
    }

    @ApiOperation("房屋详情")
    @PostMapping(value = "info")
    public ResultVO info(@RequestParam Long id){
        int status = 1;
        log.info("HouseRoomController info id：{}", id);
        HouseInfoDto data =houseInfoBiz.getHouserInfo(id,status);
        log.info("HouseRoomController info data：{}", data);
        return ResultVOUtil.success(data);
    }
}
